package org.jumiz.framework.base.util;

import org.jumiz.framework.base.exception.ParserException;

import java.util.Locale;

/**
 * 根据方法名获取字段名
 * @author jumiz
 */
public final class PropertyNameUtil {

    private static final String FIELD_START_IS = "is";
    private static final String FIELD_START_GET = "get";
    private static final String FIELD_START_SET = "set";


    public static String methodToProperty(String name) {
        if (name.startsWith(FIELD_START_IS)) {
            name = name.substring(2);
        } else {
            if (!name.startsWith(FIELD_START_GET) && !name.startsWith(FIELD_START_SET)) {
                throw new ParserException(String.format("解析方法错误'{}'. 方法需要以'is', 'get' 或者 'set' 开头.", name));
            }
            name = name.substring(3);
        }

        if (name.length() == 1 || name.length() > 1 && !Character.isUpperCase(name.charAt(1))) {
            name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
        }

        return name;
    }

    public static boolean isProperty(String name) {
        return isGetter(name) || isSetter(name);
    }

    public static boolean isGetter(String name) {
        return name.startsWith(FIELD_START_GET) && name.length() > 3 || name.startsWith(FIELD_START_IS) && name.length() > 2;
    }

    public static boolean isSetter(String name) {
        return name.startsWith(FIELD_START_SET) && name.length() > 3;
    }
}
